/* 
 * Created on 2006-10-16
 * Last modified on 2006-10-16
 * Powered by YeQiangWei.com
 */ 
package com.yeqiangwei.io;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

import com.yeqiangwei.util.Validator;

public class File {
	
	public static String separator = java.io.File.separator;
	
    /**
     * 根据含URL的文件地址提取文件名，含扩展名。
     * @param fileNameAndUrl
     * @return
     */
    public static String getFileName(String fileNameAndUrl){
        if(fileNameAndUrl==null) return null;
        int fileNameStart = fileNameAndUrl.lastIndexOf(java.io.File.separator);
        if(fileNameStart==-1) fileNameStart = fileNameAndUrl.lastIndexOf("/");
        if(fileNameStart==-1) return null;
        fileNameStart+=1;
        //if(fileNameStart>=fileNameAndUrl.length())return null;
        String str = fileNameAndUrl.substring(fileNameStart, fileNameAndUrl.length());
        return str.trim();
    }
    
    /**
     * 根据含路径的文件名提取文件扩展名
     * @param fileNameAndPath
     * @return
     */
    public static String getFileExt(String fileNameAndPath){
        if(fileNameAndPath==null) return null;
        String fileext = "";
        int extStart = fileNameAndPath.lastIndexOf(".")+1;
        if(extStart==-1)return null;  
        fileext = fileNameAndPath.substring(extStart,fileNameAndPath.length());
        return fileext;
    }
    
    /**
     * 读取文本文件内容
     * @param filePathAndName 带有完整绝对路径的文件名
     * @param encoding 文本文件打开的编码方式
     * @return 返回文本文件的内容
     * @throws IOException 
     */
    public static String readTxt(String filePathAndName,String encoding) 
    		throws IOException
    {
    	StringBuffer str = new StringBuffer("");
    	FileInputStream fs = new FileInputStream(filePathAndName);
    	InputStreamReader isr;
    	if(Validator.isEmpty(encoding)){
    		isr = new InputStreamReader(fs);
    	}else{
    		isr = new InputStreamReader(fs,encoding);
    	}
    	BufferedReader br = new BufferedReader(isr);
    	String data;
		while((data = br.readLine())!=null){
			str.append(data+"\n"); 
		}
        br.close();
	    isr.close();
        fs.close();
    	return str.toString();		
    }
    public static String readText(String filePathAndName,String encoding) 
		throws IOException
	{
		FileInputStream fs = new FileInputStream(filePathAndName);
		BufferedInputStream bis = new BufferedInputStream(fs);
		ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
		byte[] buf = new byte[1024];
		int bytesRead = 0;
		while(bytesRead >= 0){
			baos.write(buf, 0, bytesRead);
			bytesRead = bis.read(buf);
		}
		byte[] content = baos.toByteArray();
		byte[] txt = new byte[content.length];
		int ii = 0;
		for(int i=0; i<content.length; i++){
			int c = content[i];
			if(c>0){
				txt[ii]= content[i];
				ii++;
			}
		}
		baos.close();
		bis.close();
		fs.close();
		return new String(txt, 0, ii, encoding);
	}
    
    /**
     * 新建目录
     * @param folderPath 目录
     * @return 返回目录创建后的路径
     */
    public static String createFolder(String folderPath) 
    {
		java.io.File myFilePath = new java.io.File(folderPath);
		
		if(!myFilePath.exists()) {
			if(!myFilePath.mkdir()){
				folderPath = null; /* 目录创建失败返回空路径 */
			}
		}
        return folderPath;
    }
    
    /**
     * 多级目录创建
     * @param folderPath 准备要在本级目录下创建新目录的目录路径 例如 c:\myf
     * @param paths 无限级目录参数，各级目录以单数线区分 例如 a|b|c
     * @return 返回创建文件后的路径 例如 c:\myf\a\b\c
     */
    public static String createFolders(String folderPath, String paths){
    	String txts = folderPath;
    	String txt;
        txts = folderPath;
        StringTokenizer st = new StringTokenizer(paths,"|");
        for(int i=0; st.hasMoreTokens(); i++){
            txt = st.nextToken().trim();
            if(i!=0&&txts.lastIndexOf(java.io.File.separator)!=-1){ 
            	txts = createFolder(txts + java.io.File.separator + txt);   
            }else{
            	txts = createFolder(txts + txt);
            }
            if(txts==null){
            	return null;
            }
        }
    	txts+=separator;      
    	return txts;
    }
    
    /**
     * 
     * 新建文件
     * @param filePathAndName 文本文件完整绝对路径及文件名
     * @param fileContent 文本文件内容
     * @author YeQiangWei Studio by 我容易么我
     * @throws IOException 
     */
    public static void createFile(String filePathAndName, String fileContent) 
    	throws IOException 
    {
    	createFile(filePathAndName, fileContent, "UTF-8", true);  	
    }

    
    /**
     * 
     * 有编码方式的文件创建
     * @param filePathAndName 文本文件完整绝对路径及文件名
     * @param fileContent 文本文件内容
     * @param encoding 编码方式 例如 GBK 或者 UTF-8
     * @throws Exception
     * @author YeQiangWei Studio by 我容易么我
     * @throws IOException 
     */
    public static void createFile
    	(String filePathAndName, String fileContent, String encoding, boolean cover) 
    throws IOException

    {
    	if(Validator.isEmpty(filePathAndName)||Validator.isEmpty(fileContent.toString())){
    		return;
    	}
        java.io.File myFilePath = new java.io.File(filePathAndName.toString());
        /*
         * 如果文件不存在，切要求自动覆盖！
         */
        if(!cover&&myFilePath.exists()){ //不覆盖
        	//System.out.println("文件存在！"+myFilePath.exists());
            return ;
        }
        PrintWriter myFile = null;
        if(!Validator.isEmpty(encoding)){
        	myFile = new PrintWriter(myFilePath,encoding);
        }else{
        	myFile = new PrintWriter(myFilePath);
        }
        if (!myFilePath.exists()) {
            myFilePath.createNewFile();
            myFile.print(fileContent);
       		myFile.close();
        }
        else{
        	myFile.print(fileContent);
         	myFile.close();
        }
    } 
    
    
    /**
     * 删除文件
     * @param filePathAndName 文本文件完整绝对路径及文件名
     * @return Boolean 成功删除返回true遭遇异常返回false
     * @author YeQiangWei Studio by 我容易么我
     */
    public static boolean deleteFile(String filePathAndName) {
    	boolean bea = false;
    	String filePath = filePathAndName;
        java.io.File myDelFile = new java.io.File(filePath);
        if(myDelFile.exists()){
        	bea = myDelFile.delete();
        }else{
        	bea = false;
        }
        return bea;
    }
    
    /**
     * 删除文件夹
     * @param folderPath 文件夹完整绝对路径
     * @return
     */
    public static boolean deleteFolder(String folderPath) {
    	 deleteAllFile(folderPath); //删除完里面所有内容
         String filePath = folderPath;
         filePath = filePath.toString();
         java.io.File myFilePath = new java.io.File(filePath);
         return myFilePath.delete(); //删除空文件夹
    }
    
    
    /**
     * 删除指定文件夹下所有文件
     * @param path 文件夹完整绝对路径
     * @return
     * @return
     
    public static boolean deleteAllFile(String path) {
    	boolean bea = false;
    	bea = deleteFolder(path);
    	if(createFolder(path)!=null){
    		bea = true;
    	}
    	return bea;
    }*/
 
    public static boolean deleteAllFile(String path) {
    	boolean bea = false;
    	java.io.File file = new java.io.File(path);
        if (!file.exists()) {
            return bea;
        }
        if (!file.isDirectory()) {
            return bea;
        }
        String[] tempList = file.list();
        java.io.File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new java.io.File(path + tempList[i]);
            }else{
                temp = new java.io.File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                bea = temp.delete();
            }
            if (temp.isDirectory()) {
            	bea = deleteAllFile(path + File.separator + tempList[i]);//先删除文件夹里面的文件
            	//bea = deleteFolder(path + File.separator + tempList[i]);//再删除空文件夹
            }
        }
        return bea;
    }
   
    
    /**
     * 复制单个文件
     * @param oldPathFile 准备复制的文件源
     * @param newPathFile 拷贝到新绝对路径带文件名
     * @return
     * @throws IOException 
     */
    public static boolean copyFile(String oldPathFile, String newPathFile) 
    		throws IOException 
    {
        boolean bea = false;
        int bytesum = 0;
        int byteread = 0;
        java.io.File oldfile = new java.io.File(oldPathFile);
        if (oldfile.exists()) { //文件存在时
            InputStream inStream = new FileInputStream(oldPathFile); //读入原文件
            FileOutputStream fs = new FileOutputStream(newPathFile);
            byte[] buffer = new byte[1444];
            while((byteread = inStream.read(buffer)) != -1){
                bytesum += byteread; //字节数 文件大小
                fs.write(buffer, 0, byteread);
            }
            inStream.close();
            fs.close();
            bea = true;
        } 
        return bea;
    }
    
    /**
     * 复制整个文件夹的内容
     * @param oldPath 准备拷贝的目录
     * @param newPath 指定绝对路径的新目录
     * @throws IOException 
     */
    public static boolean copyFolder(String oldPath, String newPath) 
    		throws IOException 
    {
    	boolean bea = false;
    	new java.io.File(newPath).mkdirs(); //如果文件夹不存在 则建立新文件夹
    	java.io.File a = new java.io.File(oldPath);
        String[] file = a.list();
        java.io.File temp = null;
        for (int i = 0; i < file.length; i++) {
            if(oldPath.endsWith(File.separator)){
                temp=new java.io.File(oldPath+file[i]);
            }else{
                temp=new java.io.File(oldPath+File.separator+file[i]);
            }
            if(temp.isFile()){
                FileInputStream input = new java.io.FileInputStream(temp);
                FileOutputStream output = new java.io.FileOutputStream(newPath + File.separator +
                (temp.getName()).toString());
                byte[] b = new byte[1024 * 5];
                int len;
                while ((len = input.read(b)) != -1) {
                    output.write(b, 0, len);
                }
                output.flush();
                output.close();
                input.close();
            }
            else if(temp.isDirectory()){//如果是子文件夹
                copyFolder(oldPath+File.separator+file[i],newPath+File.separator+file[i]);
            }
        }
        bea = true;
        return bea;
    }
    
    /**
     * 移动文件
     * @param oldPath 文件所在的原始路径
     * @param newPath 文件将要移动到的目标路径
     * @author YeQiangWei Studio by 我容易么我
     * @throws IOException 
     */
    public static boolean moveFile(String oldPath, String newPath) 
    		throws IOException
    {
        boolean bea = copyFile(oldPath, newPath);
        if(bea){
        	bea = deleteFile(oldPath);
        }
        return  bea;
    }
    
    /**
     * 移动目录
     * @param oldPath 目录所在的原始路径
     * @param newPath 目录将要移动到的目标路径
     * @author YeQiangWei Studio by 我容易么我
     * @throws IOException 
     */
    public static boolean moveFolder(String oldPath, String newPath) throws IOException
    {
        boolean bea = copyFolder(oldPath, newPath);
        if(bea){
        	bea = deleteFolder(oldPath);
        }else{
        	//System.out.println("目录删除失败!");
        }
        return bea;
    }
    
    
    

    
}
